package com.cskaoyan.gateway.controller.user;

import com.cskaoyan.gateway.form.register.RegisterForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IUserRegister;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.KaptchaCodeRequest;
import com.mall.user.dto.KaptchaCodeResponse;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Liang Shunhao
 * @description: 用户注册
 * @date 2021/9/29 9:10
 */
@RestController
@RequestMapping("user")
public class RegisterController {

    @Reference(timeout = 3000, check = false)
    IKaptchaService kaptchaService;

    @Reference(timeout = 3000, check = false)
    IUserRegister userRegister;

    @PostMapping("register")
    @Anoymous
    public ResponseData register(@RequestBody RegisterForm registerForm, HttpServletRequest httpServletRequest) {
        // 验证码判断
        KaptchaCodeRequest request = new KaptchaCodeRequest();
        String code = registerForm.getCaptcha();
        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
        request.setUuid(uuid);
        request.setCode(code);
        // 参数校验
        request.requestCheck();
        KaptchaCodeResponse response = kaptchaService.validateKaptchaCode(request);
        if (!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            // 验证码错误
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        // 用户注册
        UserRegisterRequest register = new UserRegisterRequest();
        register.setUserName(registerForm.getUserName());
        register.setUserPwd(registerForm.getUserPwd());
        register.setEmail(registerForm.getEmail());
        // 参数校验
        register.requestCheck();
        UserRegisterResponse userResponse = userRegister.userRegister(register);
        return new ResponseUtil<>().setData(userResponse);
    }

}
